﻿using System;
using System.Collections.Generic;
using System.Linq;
using Fwql.Net.Utils;

namespace Fwql.Net.Extensions
{
    public static class CollectionExtensions
    {
        /// <summary>
        /// 添加唯一值
        /// </summary>
        /// <typeparam name = "T">集合类型</typeparam>
        /// <param name = "collection">集合</param>
        /// <param name = "value">待添加的值</param>
        /// <returns>指定值是否被成功添加</returns>
        /// <example>
        /// 	<code>
        /// 		list.AddUnique(1); // returns true;
        /// 		list.AddUnique(1); // returns false the second time;
        /// 	</code>
        /// </example>
        public static bool AddUnique<T>(this ICollection<T> collection, T value)
        {
            Guard.NotNull(collection, "collection");
            if (collection.Contains(value) == false)
            {
                collection.Add(value);
                return true;
            }
            return false;
        }

        /// <summary>
        /// 添加唯一值
        /// </summary>
        /// <typeparam name = "T">集合类型</typeparam>
        /// <param name = "collection">集合</param>
        /// <param name = "values">待添加的值</param>
        /// <returns>返回成功添加的值的数量</returns>
        public static int AddUnique<T>(this ICollection<T> collection, IEnumerable<T> values)
        {
            if (collection == null)
                throw new ArgumentNullException("collection");
            return values.Count(collection.AddUnique);
        }

    }
}